﻿using ConsoleApp.Model.Entity;
using ConsoleApp.Service;
using Quartz;
using Quartz.Impl;
using Quartz.Spi;

namespace ConsoleApp.DispatchTask
{
    public class Dispatch
    {
        private readonly ILogger<Dispatch> _logger;
        private readonly  ISchedulerFactory _schedulerFactory;  
        private readonly IJobFactory _iocJobfactory;
        private  IScheduler _scheduler;
        

        
        public Dispatch(IJobFactory iocJobfactory, ILogger<Dispatch> logger, ISchedulerFactory schedulerFactory)
        {
            this._logger = logger;
            //1、声明一个调度工厂
            this._schedulerFactory = schedulerFactory;
            this._iocJobfactory = iocJobfactory;
        }

        public void Stop()
        {
            if (_scheduler == null)
            {
                return;
            }

            if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
                _scheduler = null;
            else
            {
            }
            _logger.LogCritical("Schedule job upload as application stopped");
            Console.WriteLine("触发停止");
        }
        
        public async Task Init()
        {
            try
            {
                #region 创建单元（时间轴/载体）

                _scheduler = await _schedulerFactory.GetScheduler();
                _scheduler.JobFactory = _iocJobfactory;
                await _scheduler.Start();

                #endregion

                IJobDetail jobDetail = JobBuilder.Create<SendMessageJob>()
                    .WithIdentity("sendMessageJob","group1")
                    .WithDescription("this is send message job")
                    .Build();

                ITrigger trigger = TriggerBuilder.Create()
                    .WithIdentity("sendMessageTrigger", "group1")
                    //.WithSimpleSchedule(x => x.WithIntervalInSeconds(2).RepeatForever())//每两秒执行一次
                    .WithCronSchedule("0 55 8 ? * *")
                    .Build();
            
                await _scheduler.ScheduleJob(jobDetail, trigger);
            

                Console.WriteLine("定时任务启动");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Failed to initialize,{ex.Message}");
            }
        }


    }
}
